module mod_fftw
! double 2d fft forward and backward
implicit none
real(8),allocatable,dimension(:,:):: fftreal
complex(8),allocatable,dimension(:,:):: fftcomplex

!public dfftw_init,dfftw_r2c,dfftw_c2r,dfftw_destroy

include "fftw3.f"
integer*8,save:: plan2dr2c,plan2dc2r

contains
subroutine dfftw_init(nxi,nyi)
  implicit none
  integer::nxi,nyi,ierr
  allocate(fftreal(nxi,nyi),fftcomplex(nxi/2+1,nyi),stat=ierr)
  call dfftw_plan_dft_r2c_2d(plan2dr2c,nxi,nyi,fftreal,fftcomplex,FFTW_MEASURE)
  call dfftw_plan_dft_c2r_2d(plan2dc2r,nxi,nyi,fftcomplex,fftreal,FFTW_MEASURE)
endsubroutine

subroutine dfftw_r2c()
call dfftw_execute_dft_r2c(plan2dr2c,fftreal,fftcomplex)
endsubroutine dfftw_r2c

subroutine dfftw_c2r()
!the input fftcomplex array is destroyed.
call dfftw_execute_dft_c2r(plan2dc2r,fftcomplex,fftreal)
endsubroutine dfftw_c2r

subroutine dfftw_destroy()
  call dfftw_destroy_plan(plan2dr2c)
  call dfftw_destroy_plan(plan2dc2r)
  deallocate(fftreal,fftcomplex)
endsubroutine dfftw_destroy


end module mod_fftw

